package cn.lyjuan.payment.third.base.pay.chl.impl.ali.util;

import cn.lyjuan.base.util.RandomUtils;
import cn.lyjuan.payment.third.base.pay.chl.impl.ali.bean.AliChlCnf;
import cn.lyjuan.payment.third.base.pay.chl.impl.ali.bean.AliPayMapRes;
import cn.lyjuan.payment.third.base.pay.chl.impl.ali.bean.AliPayReq;
import cn.lyjuan.payment.third.base.pay.cst.PayConst;
import cn.lyjuan.payment.third.base.pay.vo.req.PayReq;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝手机端SDK支付提交工具
 * Created by ly on 2015/2/4.
 */
@Slf4j
public class AliWapPaySubmit {

    /**
     * 创建支付宝手机交易请求参数
     *
     * @param order   订单信息
     * @param cnf     支付平台配置信息
     * @param isDebug 是否沙箱环境
     * @return
     */
    public static AliPayMapRes createTradeExec(PayReq<AliPayReq> order, AliChlCnf cnf, boolean isDebug) {
        DefaultAlipayClient alipayClient;
        try {
            alipayClient = AlipaySubmit.makeCertAlipayClient(cnf.getCertPath(), cnf, isDebug);
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            Map<String, String> map = new HashMap<>();
            map.put("subject", order.getGoods());
            map.put("out_trade_no", RandomUtils.uuid());
            map.put("total_amount", Double.toString(order.getAmt() / 100.0));
            request.setBizContent(JSONObject.toJSONString(map));
            request.setNotifyUrl(order.getNotifyUrl());
            AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
            log.info("response {}", response.getBody());
            return new AliPayMapRes(response.getBody());
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        // todo 修改
        //return null;
    }
}
